package com.yinzifan.manager.error;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice(basePackages = "com.yinzifan.manager.controller")
public class ErrorControllerAdvice {

	
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public ResponseEntity<Map<String, Object>> handleException (Exception e) {
		Map<String, Object> errorAttributes = new HashMap<>();
		/**
		 * {
			    "timestamp": "2018-07-30 23:02:59",
			    "status": 500,
			    "error": "Internal Server Error",
			    "message": "No message available",
			    "path": "/manager/products/"
			}
		 */
		String errorCode = (String)e.getMessage();
		ErrorEnum errorEnum = ErrorEnum.getByCode(errorCode);
		errorAttributes.put("message", errorEnum.getMessage());
		errorAttributes.put("code", errorEnum.getCode());
		errorAttributes.put("canRetry", errorEnum.isCanRetry());
		errorAttributes.put("from", "com.yinzifan.manager.error.ErrorControllerAdvice");
		return new ResponseEntity<Map<String, Object>>(errorAttributes, HttpStatus.INTERNAL_SERVER_ERROR);
	}
}
